import * as articleApi from '../../api/articles';
import * as channelApi from '../../api/channels';

const api = {
    ...articleApi,
    ...channelApi,
};

// model层
export default {
    namespaced: true, // 模块必须有这句话
    state: {
        channels: [],
        articles: [],
        suggestions: [],
        myChannels: [],
    },
    mutations: {
        // 设置更改state的方法
        SET_CHANNELS (state, newValue) {
            state.channels = newValue;
        },
        SET_ARTICLES (state, newValue) {
            state.articles = newValue;
        },
        SET_SUGGESTIONS (state, newValue) {
            state.suggestions = newValue;
        },
        SET_MY_CHANNELS (state, newValue) {
            state.myChannels = newValue;
        },
    },
    actions: {
        // 发送异步请求（给页面设置state的机会）
        async updateChannels (context) {
            const res = await api.getChannels();
            context.commit('SET_CHANNELS', res.data.data.channels);
        },
        /**
         * @param { { channel_id: number, timestamp: number } } params
         */
        async updateArticles (context, params) {
            context.commit('SET_ARTICLES', []);
            const res = await api.getArticles(params);
            context.commit('SET_ARTICLES', res.data.data.results);
        },
        /**
         * @param { string } keyword
         */
        async search (context, keyword) {
            context.commit('SET_ARTICLES', []);
            const res = await api.search(keyword);
            context.commit('SET_ARTICLES', res.data.data.results);
        },
        /**
         * @param { string } keyword
         */
        async updateSearchSuggestions (context, keyword) {
            context.commit('SET_SUGGESTIONS', []);
            const res = await api.getSearchSuggestions(keyword);
            context.commit('SET_SUGGESTIONS', res.data.data.options);
        },
        async updateMyChannels (context) {
            // context.commit('SET_MY_CHANNELS', []);
            const res = await api.getMyChannels();
            context.commit('SET_MY_CHANNELS', res.data.data.channels);
        },
    },
}
